// option.cs
//
//  Copyright (C) 2008 BOUTRY Arnaud arnaud@lorphoenix.info
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License  version 2 as 
//published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//

using System;
using System.Collections;
using System.IO;

public class OptionList
{
	private Hashtable _OptionList;
	private string _OptionFile;
	public OptionList()
	{
		_OptionList = new Hashtable();
	}
	
	public OptionList(string optfile)
	{
		_OptionList = new Hashtable();
		_OptionFile = optfile;
		Load(optfile);
	}
	
	public void Load (string optionfile)
	{
		FileStream fichier = File.Open(optionfile,FileMode.Open);
		StreamReader read = new StreamReader(fichier);
		read.BaseStream.Seek(0,SeekOrigin.Begin);
		string optionstring;
		while(!read.EndOfStream)
		{
			optionstring = read.ReadLine();
			if (!optionstring.StartsWith("#"))
				_combine(optionstring);
		}
		read.Close();
		fichier.Close();
	}
	public void Save()
	{
		Save(_OptionFile);
	}
	public void Save(string optionfile)
	{
		_OptionFile = optionfile;
		_Save();
	}
	
	private void _Save()
	{
		FileStream fichier = File.Open(_OptionFile,FileMode.OpenOrCreate);
		StreamWriter w = new StreamWriter(fichier);
		w.BaseStream.Seek(0,SeekOrigin.Begin);
		foreach(object key in _OptionList.Keys)
		{
			string tmpstring =key.ToString()+"="+_OptionList[key].ToString();
			if(tmpstring!=String.Empty)
				w.WriteLine(tmpstring);
		}
		w.Flush();
		fichier.Flush();
		fichier.Close();
		w.Close();
	}
	
	private void _combine(string optionstring)
	{
		int cpos=optionstring.IndexOf("=");
		string key = optionstring.Substring(0,cpos);
		string valuekey = optionstring.Substring(cpos+1,optionstring.Length-cpos-1);
		set(key,valuekey);
	}

	public void clear()
	{
		_OptionList.Clear();
	}
	
	public ArrayList KeyList
	{
		get {
			ArrayList keylist = new ArrayList();
			foreach(object key in _OptionList.Keys)
				keylist.Add(key.ToString());
			return keylist;
		}
	}
	
	public void set(string name,Object value)
	{
		if(!_OptionList.ContainsKey(name))
			_OptionList.Add(name,value);
		else 
			_OptionList[name]=value;
	}
	
	public bool OptionValueBool(string name)
	{
		if ((string)_OptionList[name]=="1")
			return true;
		else
			return false;
	}
	public string OptionValueString(string name)
	{
		return (string)_OptionList[name];
	}
	
	public int OptionValueInt(string name)
	{
		return Int32.Parse((string)_OptionList[name]);
	}
	
}
